import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';

import postcsspxtoviewport from 'postcss-px-to-viewport-8-plugin';
import path from 'path';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';

// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd());
  const { VITE_APP_ENV, VITE_APP_BASE_API, VITE_APP_BASE_URL } = env;
  // const loder_pxtovw = pxtovw({
  //   viewportWidth: 750,
  //   viewportUnit: "vw",
  //   exclude: [/node_modules\/vant/i],
  // });
  // const vant_pxtovw = pxtovw({
  //   viewportWidth: 375,
  //   viewportUnit: "vw",
  //   exclude: [/^(?!.*node_modules\/vant)/], //忽略除vant之外的
  // });
  return {
    publicDir: 'public',
    base: VITE_APP_ENV === 'development' ? '/' : '/',
    resolve: {
      alias: {
        '@': resolve(__dirname, './src'),
      },

      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
    },
    server: {
      port: 5137,
      host: true,
      open: true,
      proxy: {
        [`${VITE_APP_BASE_API}`]: {
          target: VITE_APP_BASE_URL,
          changeOrigin: true,
          rewrite: (p) => p.replace(`${VITE_APP_BASE_API}`, ''),
          bypass(req, res, options) {
            const proxyUrl = new URL(options.rewrite(req.url) || '', options.target)?.href || '';
            req.headers['x-req-proxyUrl'] = proxyUrl
            res.setHeader('x-res-proxyUrl', proxyUrl)
          },
        },

      },
    },
    plugins: [
      vue(),
      createSvgIconsPlugin({
        // 指定 SVG图标 保存的文件夹路径
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        // 指定 使用svg图标的格式
        symbolId: 'icon-[dir]-[name]',
      }),
    ],
    css: {
      // css预处理器
      preprocessorOptions: {
        scss: {
          // 引入 mixin.scss 这样就可以在全局中使用 mixin.scss中预定义的变量了
          // 给导入的路径最后加上 ;
          additionalData: '@use "@/assets/styles/mixin.scss" as *;',
        },
      },
      postcss: {
        plugins: [],
      },
    },
  };
});
